package com.dh.jwt.auth.filter;

import java.io.IOException;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
//import org.apache.commons.logging.Log;
//import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.filter.OncePerRequestFilter;

import com.dh.jwt.auth.tip.ErrorTip;
import com.dh.jwt.config.JwtProperties;
import com.dh.jwt.enums.BizExceptionEnum;
import com.dh.jwt.utils.JwtTokenUtil;
import com.dh.jwt.utils.RenderUtil;

import io.jsonwebtoken.JwtException;

/**
 * 对客户端请求的jwt token验证过滤器
 *
 * @author fengshuonan
 * @Date 2017/8/24 14:04
 */
public class AuthFilter extends OncePerRequestFilter {

	// private final Log logger = LogFactory.getLog(this.getClass());

	@Autowired
	private JwtTokenUtil jwtTokenUtil;

	@Autowired
	private JwtProperties jwtProperties;

	@Override
	protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
			throws IOException, ServletException {
		if (request.getServletPath().equals("/" + jwtProperties.getAuthPath()) || StringUtils.containsAny(
				request.getServletPath(), "swagger", "webjars", "swagger-resources", "error", "v2/api-docs")) {
			chain.doFilter(request, response);
			return;
		}
		final String requestHeader = request.getHeader(jwtProperties.getHeader());
		String authToken = null;
		if (requestHeader != null && requestHeader.startsWith("Bearer ")) {
			authToken = requestHeader.substring(7);

			// 验证token是否过期
			try {
				boolean flag = jwtTokenUtil.isTokenExpired(authToken);
				if (flag) {
					RenderUtil.renderJson(response, new ErrorTip(BizExceptionEnum.TOKEN_EXPIRED.getCode(),
							BizExceptionEnum.TOKEN_EXPIRED.getMessage()));
					return;
				}
			} catch (JwtException e) {
				// 有异常就是token解析失败
				RenderUtil.renderJson(response, new ErrorTip(BizExceptionEnum.TOKEN_ERROR.getCode(),
						BizExceptionEnum.TOKEN_ERROR.getMessage()));
				return;
			}
		} else {
			// header没有带Bearer字段
			RenderUtil.renderJson(response,
					new ErrorTip(BizExceptionEnum.TOKEN_ERROR.getCode(), BizExceptionEnum.TOKEN_ERROR.getMessage()));
			return;
		}
		chain.doFilter(request, response);
	}
}